package com.freecloud.javabasics.design.proxy.custom.core;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @Author: maomao
 * @Date: 2020-03-01 21:20
 */
public class FreeClassLoader extends ClassLoader {

    private File classPathFiles;
    public FreeClassLoader(){
        String classPath = FreeClassLoader.class.getResource("").getPath();
        this.classPathFiles = new File(classPath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String className = FreeClassLoader.class.getPackage().getName() + "." + name;

        if(className != null){
            File classFile = new File(classPathFiles,name.replace("\\.","/") + ".class");

            if(classFile.exists()){
                FileInputStream in = null;
                ByteArrayOutputStream out= null;
                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1){
                        out.write(buff,0,len);
                    }
                    return defineClass(className,out.toByteArray(),0,out.size());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        throw new ClassNotFoundException(name);
    }
}
